/* @Description:utils/libutils.ts @author:378237242@qq.com @date:2023/10/30 */
import axios from "axios";
import Md5 from "crypto-js/md5";
import Base64 from "crypto-js/enc-base64";
import Utf8 from "crypto-js/enc-Utf8";

// 定义XfAccount类型，用于存储APPID、APISECRET、APIKEY
type XfAccount = {
  APPID: string;
  APISECRET?: string;
  APIKEY?: string;
};
// 定义ApiType类型，用于存储cws、pos、ner、dp、srl、sdp、sdgp
type ApiType = "cws" | "pos" | "ner" | "dp" | "srl" | "sdp" | "sdgp";
// 定义NlpApiType类型，用于存储ApiType数组
type NlpApiType = Array<ApiType>;
// 定义NlpPkgOption类型，用于存储xfAccount、nlpApi、text
type NlpPkgOption = {
  xfAccount: XfAccount;
  nlpApi: NlpApiType;
  text: string;
};

/**
 * 讯飞自然语言处理
 * 词法分析管理类 https://www.xfyun.cn/doc/nlp/lexicalAnalysis/API.html
 * 自然语言基础处理服务包括：词法分析、依存句法分析、语义角色标注、语义依存 (依存树) 分析、语义依存 (依存图) 分析五类，其中词法分析又可以分为：中文分词、词性标注、命名实体识别。
 */
class NlpPkg {
  xfAccount: XfAccount;
  nlpApi: NlpApiType;
  text: string;

  constructor(option: NlpPkgOption) {
    this.xfAccount = option.xfAccount;
    this.nlpApi = option.nlpApi;
    this.text = option.text;
  }

  get XPARAM() {
    return Base64.stringify(
      Utf8.parse(
        JSON.stringify({
          type: "dependent",
        }),
      ),
    );
  }

  // 获取查询结果
  async getNlpResult() {
    const PromiseArr = this.nlpApi.map((item) => {
      return axios.request({
        url: `http://ltpapi.xfyun.cn/v1/${item}`,
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          "X-Appid": this.xfAccount.APPID,
          "X-CurTime": Math.floor(new Date().getTime() / 1000),
          "X-Param": this.XPARAM,
          "X-CheckSum": Md5(
            this.xfAccount.APIKEY +
              Math.floor(new Date().getTime() / 1000) +
              this.XPARAM,
          ).toString(),
        },
        transformRequest: [
          function (data) {
            // 对发送的 data 进行任意转换处理
            // console.log(encodeURIComponent(data.text));
            return "text=" + encodeURIComponent(data.text);
          },
        ],
        data: {
          text: this.text,
        },
      });
    });
    // TODO: 错误处理
    const result = await Promise.all(PromiseArr);
    const res = {};
    result.forEach((item) => {
      if (Object.keys(item.data.data).length > 0) {
        res[Object.keys(item.data.data)[0]] =
          item.data.data[Object.keys(item.data.data)[0]];
      }
    });
    return res;
  }
}

export { NlpPkg };
